<template>
  <div class="addSpace">
    <el-card>
      <el-form ref="form" :model="form">
        <el-form-item label="广告位名称" prop="name" :rules="rules">
          <el-input v-model="form.name" size="mini"></el-input>
        </el-form-item>
        <el-form-item class="btn">
          <el-button type="primary" size="mini" @click="onSubmit">提交</el-button>
          <el-button size="mini" @click="resetForm" v-if="isShow">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getSpaceSaveOrUpdate, getAdSpaceById } from '@/services/ad'
export default {
  name: 'addSpace',
  data () {
    return {
      form: {},
      rules: {
        name: [
          { required: true, message: '请输入广告位名称', trigger: 'blur' }
        ]
      },
      id: '',
      isShow: true
    }
  },
  created () {
    this.id = this.$route.params.id
    if (this.id) {
      this.isShow = false
      this.getAdSpaceById()
    }
  },
  methods: {
    async onSubmit () {
      await this.$refs.form.validate()
      const { data } = await getSpaceSaveOrUpdate(this.form)
      console.log(data)
      if (data.state === 1) {
        this.$message.success('提交成功')
        this.$router.push({ name: 'advertise-space' })
      }
    },
    // 重置表单
    resetForm () {
      this.$refs.form.resetFields()
    },
    // 根据Id获取广告位信息
    async getAdSpaceById () {
      const { data } = await getAdSpaceById(this.id)
      console.log(data)
      if (data.state === 1) {
        this.form = data.content
      }
    }
  }
}
</script>

<style>
.el-form-item__label{
  width: 100px;
}
.el-input{
  width: 35%;
}
.btn{
  margin-left: 50px;
}
</style>
